package com.thread;

import java.util.concurrent.TimeUnit;

/**
 * @author: mayu
 * @date: 2021年04月12日 14:53
 */
public class TestThreadLocal {
    static ThreadLocal<Person> tl = new ThreadLocal<>();

    public static void main(String[] args) {
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            tl.set(new Person("lisi"));
            System.out.println(tl.get().name);
            //避免内存泄漏
            tl.remove();
        }).start();


        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            tl.set(new Person("wangwu"));
            System.out.println(tl.get().name);
            //避免内存泄漏
            tl.remove();
        }).start();

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        tl.set(new Person("maliu"));
        System.out.println(tl.get().name);
        //避免内存泄漏
        tl.remove();
    }

    static class Person {
        private String name = "zhangsan";

        public Person(String name) {
            this.name = name;
        }
    }
}
